/*
 * Copyright (C) 2016 Nishant Srivastava
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package github.nisrulz.easydeviceinfo.base;

import ohos.app.Context;
import ohos.location.Location;
import ohos.location.Locator;
import ohos.security.SystemPermission;
import ohos.security.permission.NeedsPermission;

/**
 * EasyLocation Mod Class
 * <p>
 * You need to declare the below permission in the manifest file to use this properly
 * <p>
 * For Network based location
 * SystemPermission.LOCATION
 * <p>
 * For more accurate location updates via GPS and network both
 * SystemPermission.LOCATION_IN_BACKGROUND
 *
 * @since 2021-06-10
 */
public class EasyLocationMod {
    private final boolean hasFineLocationPermission;
    private final boolean hasCoarseLocationPermission;
    private Locator locator;

    /**
     * Instantiates a new Easy location mod.
     *
     * @param context the context
     */
    public EasyLocationMod(Context context) {
        hasFineLocationPermission =
            PermissionUtil.hasPermission(context, SystemPermission.LOCATION);
        hasCoarseLocationPermission =
            PermissionUtil.hasPermission(context, SystemPermission.LOCATION_IN_BACKGROUND);
        if (hasCoarseLocationPermission || hasFineLocationPermission) {
            locator = new Locator(context);
        }
    }

    /**
     * Get lat long double [ ].
     *
     * @return the double [ ]
     */
    @NeedsPermission(all = {
        SystemPermission.LOCATION,
        SystemPermission.LOCATION_IN_BACKGROUND
    })
    public final double[] getLatLong() {
        double[] gps = new double[2];
        gps[0] = 0;
        gps[1] = 0;
        if (locator != null && (hasCoarseLocationPermission || locator.getCachedLocation() != null)) {
            Location lastKnownLocation = locator.getCachedLocation();
            if (null == lastKnownLocation) return gps;
            gps[0] = lastKnownLocation.getLatitude();
            gps[1] = lastKnownLocation.getLongitude();
        }
        return gps;
    }

    private Location getBetterLocation(final Location location1, final Location location2) {
        if (location1.getAccuracy() >= location2.getAccuracy()) {
            return location1;
        } else {
            return location2;
        }
    }
}
